import * as THREE from '../animate1/three.weapp.js'
GLTFLoader = getGLTFLoader(THREE);
            
let { SkeletonUtils } = getSkeletonUtils(THREE);
const deviceOrientationControl = require('DeviceOrientationControl.js');
// const { getGLTFLoader } = require('GLTFLoader.js');
import getGLTFLoader from 'GLTFLoader' 
import getSkeletonUtils from 'SkeletonUtils.js';

const deviceMotionInterval = 'ui';
var camera, scene, renderer;
var canvas,poid;
var touchX, touchY, device = {};
var lon, lat,GLTFLoader, gradient, clock, mixer, controls, action, activeAction, face, actions;
// var THREE;
var seletedModel, requestId,requestId2,monsmsg,name1,name2,Url,isstop=1,times=1,pages,prevPage;
var isDeviceMotion = false;
var isAndroid = false;
var last_lon, last_lat, last_device = {};
var cameraFrame = {};
var cameraRTT, sceneRTT, planeTexture, models;
var MODELS = [];

var worldScene = null;
var mixers = []; 
var numLoadedModels = 0;
var UNITS=[]
// 获取参数:画布id，模型名、网格名、（动画名）
function initThree(canvasId,name1,modelUrl,callback) {
    Url = modelUrl
    console.log('Url',Url)
    MODELS = [
        { name : name1}
    ];
    UNITS=[{
        modelName: name1,
        position: { x: 2, y: -4, z: 0 },
        scale: 200,
        meshName: 'body11',
    },{
        modelName: name1,
        position: { x: 2, y: -4, z: 0 },
        scale: 2,
        meshName: 'mixamorig_Hips',
    }]
    wx.createSelectorQuery()
        .select('#' + canvasId)
        .node()
        .exec((res) => {
			canvas = new THREE.global.registerCanvas(res[0].node)
            clock = new THREE.Clock();

            worldScene = new THREE.Scene();
            if (typeof callback === 'function') {
                callback(THREE);
            }
            playani()
            animate()
            console.log('模型绑定到画布')
        });
}
// 初始化场景，设置场景参数，添加光源，设置完之后加载模型
function initScene() {
    lon = 30;
    lat = 190;
    camera = new THREE.PerspectiveCamera(75,
        canvas.width / canvas.height,
        1,
        1000);
    scene = new THREE.Scene();
    worldScene.add(new THREE.AmbientLight(0xffffff));
    var light = new THREE.HemisphereLight(0xffffff, 0x444444);
    light.position.set(0, 20, 0);
    worldScene.add(light);
    light = new THREE.DirectionalLight(0xffffff);
    light.position.set(0, 20, 10);
    worldScene.add(light);
    console.log('worldScene',worldScene)
    renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true,
    });
    console.log('canvas size', canvas.width, canvas.height);
    renderer.setSize(canvas.width, canvas.height);
    // camera.position.set( 3, 3, 6 );
    camera.position.set( 2, 1, 8 );
    loadModels();
}
//判断模型数量，调用下载模型方法
function loadModels() {
    
    pages = getCurrentPages();
    prevPage = pages[pages.length-1]
    prevPage.hidetishi()
    wx.showLoading({
        title: 'Loading Model...',
    });

    for (var i = 0; i < MODELS.length; ++i) {
        var m = MODELS[i];
        loadGltfModel(m, function () {
            ++numLoadedModels;
            if (numLoadedModels === MODELS.length) {
                console.log("All models loaded, time to instantiate units...");
                start2(0)   //加载完模型后播放动画
            }
        });
        console.log('模型加载数量',i+1)
    }
}
//加载器加载模型，onloaded是方法，调用加载动画的方法start2
function loadGltfModel(model, onLoaded) {
    console.log('Url',Url)
    var loader = new GLTFLoader();
    var modelName = "models/" + model.name + ".glb";
    // loader.load("https://www.juquduo.com/static/models/cygy/jiangjun.glb", function (gltf) {
    // loader.load("https://www.juquduo.com/static/models/cygy/general.glb", function (gltf) {
    // loader.load("http://192.168.1.104:5500/fbx文件/jiangjun.glb", function (gltf) {
    // loader.load('http://192.168.1.107:5500/fbx文件/act.glb', function (gltf) {
    loader.load(Url, function (gltf) {
        wx.hideLoading()//隐藏加载动画
        prevPage.showbtn()
        var scene = gltf.scene;
        model.animations = gltf.animations;
        model.scene = scene;
        gltf.scene.traverse(function (object) {
            if (object.isMesh) {
                object.castShadow = true;
            }
        });
        console.log("Done loading model", model.name);
        onLoaded();
    });
}
// 添加动画时,用于获取模型
function getModelByName(name) {
    for (var i = 0; i < MODELS.length; ++i) {
        if (MODELS[i].name === name) {
            return MODELS[i];
        }
    }
    return null;
}
// 添加动画
function start2(isstop){
    // 在场景里，删掉之前的动画，保留灯光等效果
    if(worldScene.children.length>3){worldScene.children.splice(3)}
    
    //获取模型、场景、网格、播放器、动画动作 等对象
    var u = UNITS[0];
    var model = getModelByName(u.modelName);
    console.log('model',model)
    var clonedScene = SkeletonUtils.clone(model.scene);
    clonedScene.scale.set(u.scale, u.scale, u.scale);   //设置场景，设置缩放倍数、观察位置
    clonedScene.position.set(u.position.x, u.position.y, u.position.z);
    clonedScene.rotation.y = 0.3;
    var clonedMesh = clonedScene.getObjectByName('mixamorig_Hips');
    console.log('clonedMesh',clonedMesh)
    worldScene.add(clonedScene);        //场景添加到屏幕场景
    console.log('添加完动作',worldScene.children)     //查看屏幕场景的当前信息
    // console.log(model.animations)
    var mixer = model.mixer = new THREE.AnimationMixer(model);      //获取播放器
    var clip = model.animations[isstop]
    if(clip){
        console.log('动画已播放')
        var AnimationAction =mixer.clipAction( clip, clonedMesh)    //给播放器添加动画
        // 设置动画动作
        // AnimationAction.setLoop( THREE.LoopOnce )   //播放一次就停止
        AnimationAction.clampWhenFinished = true;   //播放停止在最后一帧
        AnimationAction.play();
        mixers.push(mixer);
    }
}
//动画，计算手机移动，旋转模型
function animate() {
    
    requestId2 = canvas.requestAnimationFrame(animate);

    if (lon !== last_lon ||
        lat !== last_lat) {

        last_lon = lon;
        last_lat = lat;

        deviceOrientationControl.modelRotationControl(seletedModel, lon, lat, gradient, THREE);
    }

    if (last_device.alpha !== device.alpha ||
        last_device.beta !== device.beta ||
        last_device.gamma !== device.gamma) {

        last_device.alpha = device.alpha;
        last_device.beta = device.beta;
        last_device.gamma = device.gamma;

        if (isDeviceMotion) {
            deviceOrientationControl.deviceControl(camera, device, THREE, isAndroid);
        }
    }
    renderer.render(worldScene, camera);
}
// 每帧刷新，每帧调用一次，用于播放动画，把sence渲染到屏幕
function playani() {
    var dt = clock.getDelta();
    // if (mixer) mixer.update(dt);
    for (var i = 0; i < mixers.length; ++i) {
        mixers[i].update(dt);
    }
    requestId = canvas.requestAnimationFrame(playani,animate);
    renderer.render(worldScene, camera);
    // console.log('每帧刷新')
  }
// 停止动画，修改参数，停止渲染的request
function stopanimate() {
    if (canvas && requestId) {
        canvas.cancelAnimationFrame(requestId);
        canvas.cancelAnimationFrame(requestId2);
    }
    worldScene=''
    numLoadedModels = 0
}

function onTouchstart(event) {
    var touch = event.touches[0];
    touchX = touch.x;
    touchY = touch.y;
}

function onTouchmove(event) {
    var touch = event.touches[0];
    var moveX = touch.x - touchX;
    var moveY = touch.y - touchY;
    lon += moveX;
    lat += moveY;
    touchX = touch.x;
    touchY = touch.y;
    gradient = Math.abs(moveX / moveY);
}

function startDeviceMotion(_isAndroid) {
    isDeviceMotion = true;
    isAndroid = _isAndroid;
    wx.onDeviceMotionChange(function (_device) {
        device = _device;
    });
    wx.startDeviceMotionListening({
        interval: deviceMotionInterval,
        success: function () {
            console.log('startDeviceMotionListening', 'success');
        },
        fail: function (error) {
            console.log('startDeviceMotionListening', error);
        }
    });
}

function stopDeviceMotion() {
    isDeviceMotion = false;
    wx.offDeviceMotionChange();
    wx.stopDeviceMotionListening({
        success: function () {
            console.log('stopDeviceMotionListening', 'success');
        },
        fail: function (error) {
            console.log('stopDeviceMotionListening', error);
        }
    });
}

function setCameraFrame(_cameraFrame) {
    cameraFrame = _cameraFrame;
}
module.exports = {
    initThree,
    initScene,
    onTouchstart,
    onTouchmove,
    startDeviceMotion,
    stopDeviceMotion,
    stopanimate,
    setCameraFrame,
    UNITS,
    start2,
}